package logic

import (
	"context"
	"database/sql"
	"time"

	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/internal/svc"
	"gitee.com/gao-deguang/easy-chat/apps/social/rpc/social"
	"gitee.com/gao-deguang/easy-chat/apps/social/socialmodels"
	"gitee.com/gao-deguang/easy-chat/pkg/constant"
	"gitee.com/gao-deguang/easy-chat/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var (
	ErrFriendreqBeforeAndPass   = xerr.NewMsg("好友已经申请过并已通过")
	ErrFriendreqBeforeAndRefuse = xerr.NewMsg("好友申请并已拒绝")
)

type FriendPutInHandleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFriendPutInHandleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FriendPutInHandleLogic {
	return &FriendPutInHandleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FriendPutInHandleLogic) FriendPutInHandle(in *social.FriendPutInHandleReq) (*social.FriendPutInHandleResp, error) {
	// todo: add your logic here and delete this line
	//查询申请记录
	friendreq, err := l.svcCtx.FriendRequestsModel.FindOne(l.ctx, uint64(in.FriendReqId))
	if err != nil {
		return nil, errors.Wrapf(xerr.NewDBErr(), "find FriendReq by fid err :%v req:%v ", err, in.FriendReqId)
	}

	//没有记录直接返回
	if friendreq == nil {
		return nil, errors.New("没有查询到请求记录")
	}
	//有记录再具体处理//是否已经处理过了
	switch constant.HandleResult(friendreq.HandleResult.Int64) {
	case constant.PassHandelResult:
		return nil, errors.WithStack(ErrFriendreqBeforeAndPass)
	case constant.RefuseHandelResult:
		return nil, errors.WithStack(ErrFriendreqBeforeAndRefuse)
	}

	friendreq.HandleResult.Int64 = int64(in.HandelResult)

	err = l.svcCtx.FriendRequestsModel.Trans(l.ctx, func(ctx context.Context, s sqlx.Session) error {
		if err := l.svcCtx.FriendRequestsModel.Update(l.ctx, s, friendreq); err != nil {
			return errors.Wrapf(xerr.NewDBErr(), "updata friend request err :%v req:%v", err, friendreq)
		}

		if constant.HandleResult(in.HandelResult) != constant.PassHandelResult {
			return nil
		}

		friends := []*socialmodels.Friends{
			{
				UserId:    friendreq.ReqUid,
				FriendUid: friendreq.UserId,
				Remark: sql.NullString{
					String: "",
					Valid:  true,
				},
				AddSource: sql.NullInt64{
					Int64: 0,
					Valid: true,
				},
				CreatedAt: sql.NullTime{
					Time:  time.Now(),
					Valid: true,
				},
			},
			{
				UserId:    friendreq.UserId,
				FriendUid: friendreq.ReqUid,
				Remark: sql.NullString{
					String: "",
					Valid:  true,
				},
				AddSource: sql.NullInt64{
					Int64: 0,
					Valid: true,
				},
				CreatedAt: sql.NullTime{
					Time:  time.Now(),
					Valid: true,
				},
			},
		}

		_, err = l.svcCtx.FriendsModel.Inserts(l.ctx, s, friends...)
		if err != nil {
			return errors.Wrapf(xerr.NewDBErr(), "inserts friends err:%v friends:%v", err, friends)
		}
		return nil

	})
	return &social.FriendPutInHandleResp{}, nil
}
